class HttpError extends Error {
	constructor(response) {
		super(`${response.status} for ${response.url}`)
		this.name = this.constructor.name // HttpError
		this.response = response
	}
}

async function loadJson(url) {
	const res = await fetch(url)

	if (res.status == 200) {
		return res.json()
	}

	throw new HttpError(res)
}

// 询问用户名，直到 github 返回一个合法的用户
async function demoGithubUser() {
	let user

	while (true) {
		let name = prompt('Enter a name?', 'iliakan')

		try {
			user = await loadJson(`https://api.github.com/users/${name}`)
			break // 没有 error，退出循环
		} catch (error) {
			if (error instanceof HttpError && error.response.status == 404) {
				// 循环将在 alert 后继续
				console.log('No such user, please reenter.')
			} else {
				// 未知的 error，再次抛出（rethrow）
				throw error
			}
		}
	}

	console.log(`Full name: ${user.name}.`)
	return user
}

demoGithubUser()
